package com.oracle.zebrafreelytraveling.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.facebook.drawee.view.SimpleDraweeView;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResViewSpotList;
import com.oracle.zebrafreelytraveling.data.model.IntroBase;
import com.oracle.zebrafreelytraveling.net.HttpManager;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.CommonAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.MultiItemTypeAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.LoadMoreWrapper;
import com.oracle.zebrafreelytraveling.ui.fragment.IntroSlideDialogFragment;
import com.oracle.zebrafreelytraveling.utils.ClassInfoUtil;
import com.oracle.zebrafreelytraveling.utils.ToastUtil;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yydcnjjw on 2017/7/28.
 * 景点分类activity
 */

public class ClassifyViewSpotActivity extends BaseActitvity {

    private static final String CITY_ID = "cityId";

    private RecyclerView mViewSpotRecycleView;
    private CommonAdapter<ResViewSpotList.ResultBean> mViewSpotAdapter;
    private LoadMoreWrapper mLoadMoreWrapper;
    private ViewHolder mViewSpotViewHolder;
    private SimpleDraweeView mViewSpotImage;
    private List<ResViewSpotList.ResultBean> mViewSpotList;
    private SwipeRefreshLayout mUpdataViewSpotRefresh;
    //记录页数
    private int page = 1;

    private Disposable mDisposable;

    private boolean isDataNull = false;

    private int cityId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getInTentData();
        initView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_view_spot_classify;
    }

    private void getInTentData(){
        Intent intent = getIntent();
        cityId = intent.getIntExtra(CITY_ID, 0);
    }

    private void initView(){
        mUpdataViewSpotRefresh = (SwipeRefreshLayout) findViewById(R.id.view_spot_refresh);
        mUpdataViewSpotRefresh.setOnRefreshListener(() -> updataViewSpotList(Constant.GET_DATA_TYPE_NOMAL));
        mViewSpotRecycleView = (RecyclerView) findViewById(R.id.view_spot_recycle);
        mViewSpotList = new ArrayList<>();
        mViewSpotRecycleView.setLayoutManager(new LinearLayoutManager(this));
        mViewSpotAdapter = new CommonAdapter<ResViewSpotList.ResultBean>(this, R.layout.item_view_spot, mViewSpotList) {
            @Override
            protected void convert(ViewHolder holder, ResViewSpotList.ResultBean resultBean, int position) {
                mViewSpotImage = holder.getView(R.id.view_spot_image);
                mViewSpotImage.setImageURI(resultBean.getImgurl());
                holder.setText(R.id.view_spot_name, resultBean.getTitle());
                holder.setText(R.id.view_spot_Introduce, resultBean.getGrade());
            }
        };
        mViewSpotAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                IntroBase base = new IntroBase();
                base.setIntroName(mViewSpotList.get(position).getTitle());
                base.setIntroImage(mViewSpotList.get(position).getImgurl());
                base.setIntroLocation(mViewSpotList.get(position).getAddress());
                IntroSlideDialogFragment.newInstance(base, Integer.parseInt(mViewSpotList.get(position).getSid()));
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        initLoadMoreWrapper();
        mViewSpotRecycleView.setAdapter(mLoadMoreWrapper);
    }

    private void initLoadMoreWrapper(){
        mLoadMoreWrapper = new LoadMoreWrapper(mViewSpotAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.footer_loading);
        mLoadMoreWrapper.setOnLoadMoreListener(viewHolder -> {
            mViewSpotViewHolder = viewHolder;
            if (!isDataNull){
                updataViewSpotList(Constant.GET_DATA_TYPE_LOADMORE);
            } else {
                viewHolder.getConvertView().setVisibility(View.GONE);
            }
        });
    }

    private void updataViewSpotList(int type){
        HttpManager.getInstance().getService(Constant.VIEW_API)
                .getViewSpotList(cityId, page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResViewSpotList>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }
                    @Override
                    public void onNext(@NonNull ResViewSpotList resViewSpot) {
                        ToastUtil.showToast(resViewSpot.getReason());
                        if (resViewSpot.getError_code() != Constant.API_SUCCESS){
                            // TODO: 2017/8/11 模拟数据
                            Log.d("adadada","adadadadadadad");
                            mViewSpotList.addAll(ClassInfoUtil.getViewSpotList());
                            mLoadMoreWrapper.notifyDataSetChanged();
                            isDataNull = true;
                            page = 0;
                            return;
                        }
                        if (type == Constant.GET_DATA_TYPE_LOADMORE){
                            mViewSpotList.addAll(resViewSpot.getResult());
                        } else {
                            mViewSpotList.clear();
                            mViewSpotList.addAll(resViewSpot.getResult());
                        }
                        isDataNull = false;
                        mLoadMoreWrapper.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("viewSpotListUpdataError", e.getMessage());
                        mUpdataViewSpotRefresh.setRefreshing(false);
                        mViewSpotViewHolder.getConvertView().setVisibility(View.GONE);
                    }
                    @Override
                    public void onComplete() {
                        mUpdataViewSpotRefresh.setRefreshing(false);
                        mViewSpotViewHolder.getConvertView().setVisibility(View.GONE);
                    }
                });
        page++;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清除 Disposable
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        page = 0;
    }

    public static void startViewSpotActivity(Activity activity, int cityId){
        Intent intent = new Intent(activity, ClassifyViewSpotActivity.class);
        intent.putExtra(CITY_ID, cityId);
        activity.startActivity(intent);
    }
}
